import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;

/// WebView 加载网页页面
class ArticleView extends StatefulWidget {
  /// 标题
  String title;

  /// 链接
  String data;

  ArticleView({Key key, @required this.title, @required this.data})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new _ArticleViewState();
  }
}

class _ArticleViewState extends State<ArticleView> {
  bool isLoad = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [
              Theme.of(context).backgroundColor,
              Theme.of(context).primaryColorLight,
            ],
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter,
                tileMode: TileMode.clamp)),
        child: Scaffold(
            backgroundColor: Colors.transparent,
            body: SingleChildScrollView(
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: openInHtml(widget.data),
                  )
                ],
              ),
            )));
  }

  Widget openInHtml(htmldata) {
    return Html(
      data: htmldata,
      padding: EdgeInsets.all(8.0),
      linkStyle: const TextStyle(
        color: Colors.redAccent,
        decorationColor: Colors.redAccent,
        decoration: TextDecoration.underline,
      ),
      onLinkTap: (url) {
        print("Opening $url...");
      },
      onImageTap: (src) {
        print(src);
      },
      //Must have useRichText set to false for this to work
      customRender: (node, children) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "custom_tag":
              return Column(children: children);
          }
        }
        return null;
      },
      customTextAlign: (dom.Node node) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "p":
              return TextAlign.justify;
          }
        }
        return null;
      },
      customTextStyle: (dom.Node node, TextStyle baseStyle) {
        if (node is dom.Element) {
          switch (node.localName) {
            case "p":
              return baseStyle.merge(TextStyle(height: 2, fontSize: 20));
          }
        }
        return baseStyle;
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
